class Solution
{
public:
    bool carPooling(vector<vector<int>> &trips, int capacity)
    {
        auto compare = [](auto &l, auto &r)
        {
            return l[1] < r[1];
        };
        sort(trips.begin(), trips.end(), compare);
        unordered_map<int, int> offCount;
        priority_queue<int, vector<int>, greater<int>> nextOffPos;
        int curCount = 0;
        for (auto &trip : trips)
        {
            while (!nextOffPos.empty() && trip[1] >= nextOffPos.top())
            {
                curCount -= offCount[nextOffPos.top()];
                offCount[nextOffPos.top()] = 0;
                nextOffPos.pop();
            }
            if (curCount + trip[0] > capacity)
            {
                return false;
            }
            curCount += trip[0];
            offCount[trip[2]] += trip[0];
            nextOffPos.push(trip[2]);
        }
        return true;
    }
};